package org.monitoringtools.manager;

import java.nio.channels.Channel;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.monitoringtools.elements.Monitor;

public class ChannelMonitorManager {

    private final Map<String, Monitor> channels = initChannels();

    private String[] monitorIds;

    private final Date monitoringStart = new Date();

    public ChannelMonitorManager(String... monitorIds) {
        this.monitorIds = monitorIds;
    }

    public Monitor getChannel(String id) {
        return this.channels.get(id);
    }

    private Map<String, Monitor> initChannels() {
        final Map<String, Monitor> map = new HashMap<String, Monitor>();

        for (String id : this.monitorIds)
            map.put(id, new Monitor(id));

        return map;
    }

    private long countFailureHitsByChannel(String id) {
        return this.channels.get(id).countFailureHits();
    }

    public long countFailureHits() {
        long total = 0;
        for (String id : this.monitorIds)
            total += countFailureHitsByChannel(id);

        return total;
    }

    private long countHitsByChannel(String id) {
        return this.channels.get(id).countHits();
    }

    public long countTotal() {
        long total = 0;
        for (String id : this.monitorIds)
            total += countHitsByChannel(id);

        return total;
    }

    private long getCountSuccessOperationsPerChannel(String id) {
        return this.channels.get(id).countSuccessHits();
    }

    public long countSuccess() {
        long total = 0;
        for (String id : this.monitorIds)
            total += getCountSuccessOperationsPerChannel(id);

        return total;
    }

    public Date getMonitoringStart() {
        return monitoringStart;
    }

    public synchronized void logFailure(Channel channel) {
        this.channels.get(channel).logFailure();
    }

    public synchronized void logSuccess(Channel channel) {
        this.channels.get(channel).logSuccess();
    }

    public long countHits(String id) {
        if (this.channels.get(id) != null)
            return this.channels.get(id).countHits();

        return 0;
    }

    public long countSuccessHits(String id) {
        if (this.channels.get(id) != null)
            return this.channels.get(id).countSuccessHits();

        return 0;
    }

    public long countFailureHits(String id) {
        if (this.channels.get(id) != null)
            return this.channels.get(id).countFailureHits();

        return 0;
    }

    public void reset() {
        initChannels();
    }
}
